<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar">
      <div class="logo">
        <h3 v-if="!isCollapse">互阅侠管理</h3>
        <span v-else>互</span>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        router
        @select="handleMenuSelect"
      >
        <!-- 动态渲染菜单 -->
        <template v-for="(menu, index) in menuList" :key="index">
          <!-- 没有子菜单的情况 -->
          <el-menu-item v-if="!menu.children" :index="menu.path">
            <el-icon>
              <component :is="getMenuIcon(menu.path)" />
            </el-icon>
            <template #title>{{ menu.title }}</template>
          </el-menu-item>
          
          <!-- 有子菜单的情况 -->
          <el-sub-menu v-else :index="getParentPath(menu.path)">
            <template #title>
              <el-icon>
                <component :is="getMenuIcon(getParentPath(menu.path))" />
              </el-icon>
              <span>{{ getParentTitle(menu.path) }}</span>
            </template>
            <el-menu-item 
              v-for="child in menu.children" 
              :key="child.path"
              :index="child.path"
            >
              {{ child.title }}
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleCollapse"
            class="collapse-btn"
          >
            <el-icon><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
          </el-button>
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item
              v-for="item in breadcrumbList"
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" />
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username || '未登录' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <!-- 退出登录 -->
                <el-dropdown-item @click="logout" command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 标签页 -->
      <div class="tabs-container">
        <el-tabs
          v-model="activeTab"
          type="card"
          closable
          @tab-remove="removeTab"
          @tab-click="handleTabClick"
        >
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.name"
            :label="tab.title"
            :name="tab.name"
          >
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 主内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, markRaw } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  House,
  User,
  Document,
  Setting,
  Fold,
  Expand,
  ArrowDown,
  Menu as IconMenu
} from '@element-plus/icons-vue'
import { useTabsStore } from '../store/tabs'
import { useUserStore } from '../store/user'

const route = useRoute()
const router = useRouter()
const tabsStore = useTabsStore()
const userStore = useUserStore()

// 侧边栏折叠状态
const isCollapse = ref(false)

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 标签页相关
const tabs = computed(() => tabsStore.tabs)
const activeTab = computed({
  get: () => tabsStore.activeTab,
  set: (val) => tabsStore.setActiveTab(val)
})

// 处理路由数据，生成菜单列表
const menuList = computed(() => {
  // 获取路由配置
  const routes = router.options.routes
  
  // 找到主布局路由（包含children的路由）
  const mainRoute = routes.find(route => route.path === '/' && route.children)
  
  if (!mainRoute || !mainRoute.children) return []
  
  // 处理菜单分组
  const menuGroups = {}
  
  mainRoute.children.forEach(route => {
    if (!route.meta) return
    
    const pathParts = route.path.split('/')
    
    // 如果是一级菜单
    if (pathParts.length === 1) {
      menuGroups[route.path] = {
        path: `/${route.path}`,
        title: route.meta.title,
        children: null
      }
    } 
    // 如果是二级菜单
    else if (pathParts.length === 2) {
      const parentPath = pathParts[0]
      
      if (!menuGroups[parentPath]) {
        menuGroups[parentPath] = {
          path: `/${parentPath}`,
          title: getParentTitle(`/${route.path}`),
          children: []
        }
      }
      
      menuGroups[parentPath].children.push({
        path: `/${route.path}`,
        title: route.meta.title
      })
    }
  })
  
  return Object.values(menuGroups)
})

// 获取菜单图标
const getMenuIcon = (path) => {
  const iconMap = {
    '/dashboard': House,
    '/user': User,
    '/content': Document,
    '/settings': Setting,
    'default': IconMenu
  }
  
  return iconMap[path] || iconMap.default
}

// 获取父级路径
const getParentPath = (path) => {
  const parts = path.split('/')
  if (parts.length <= 2) return path
  return `/${parts[1]}`
}

// 获取父级标题
const getParentTitle = (path) => {
  const parentPath = getParentPath(path)
  const titleMap = {
    '/user': '用户管理',
    '/content': '内容管理'
  }
  
  return titleMap[parentPath] || '未知菜单'
}

// 面包屑导航
const breadcrumbList = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    path: item.path,
    title: item.meta.title
  }))
})

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  // 查找选中的菜单项
  let menuInfo = null
  
  // 遍历菜单列表查找匹配的路径
  for (const menu of menuList.value) {
    if (menu.path === index) {
      menuInfo = {
        name: getRouteName(index),
        title: menu.title,
        path: index
      }
      break
    } else if (menu.children) {
      const child = menu.children.find(item => item.path === index)
      if (child) {
        menuInfo = {
          name: getRouteName(index),
          title: child.title,
          path: index
        }
        break
      }
    }
  }
  
  if (menuInfo) {
    tabsStore.addTab(menuInfo)
    tabsStore.setActiveTab(menuInfo.name)
  }
}

// 根据路径获取路由名称
const getRouteName = (path) => {
  // 移除开头的斜杠
  const cleanPath = path.startsWith('/') ? path.substring(1) : path
  // 将路径转换为驼峰命名
  return cleanPath.split('/').map((part, index) => {
    if (index === 0) return part
    return part.charAt(0).toUpperCase() + part.slice(1)
  }).join('')
}

// 移除标签页
const removeTab = (targetName) => {
  tabsStore.removeTab(targetName)
}

// 点击标签页
const handleTabClick = (tab) => {
  // Element Plus v2中tab对象的结构
  const tabName = tab.paneName
  
  const targetTab = tabs.value.find(t => t.name === tabName)
  if (targetTab) {
    router.push(targetTab.path)
  }
}

// 处理用户下拉菜单
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      console.log('个人中心')
      break
    case 'logout':
      // 清除用户信息和token
      userStore.logout()
      // 清除标签页
      tabsStore.tabs.forEach(tab => {
        tabsStore.removeTab(tab.name)
      })
      // 提示用户
      ElMessage.success('已退出登录')
      // 跳转到登录页
      router.push('/login')
      break
  }
}

// 监听路由变化，自动添加标签页
watch(
  () => route.path,
  (newPath) => {
    if (newPath !== '/') {
      // 查找当前路由对应的菜单项
      let menuInfo = null
      
      // 遍历菜单列表查找匹配的路径
      for (const menu of menuList.value) {
        if (menu.path === newPath) {
          menuInfo = {
            name: getRouteName(newPath),
            title: menu.title,
            path: newPath
          }
          break
        } else if (menu.children) {
          const child = menu.children.find(item => item.path === newPath)
          if (child) {
            menuInfo = {
              name: getRouteName(newPath),
              title: child.title,
              path: newPath
            }
            break
          }
        }
      }
      
      // 如果找到匹配的菜单项，添加标签页
      if (menuInfo) {
        tabsStore.addTab(menuInfo)
        tabsStore.setActiveTab(menuInfo.name)
      }
    }
  },
  { immediate: true }
)

// 退出登录
const logout = () => {
  
  localStorage.removeItem("loginUser")
  // 清除标签页
  tabsStore.tabs.forEach(tab => {
    tabsStore.removeTab(tab.name)
  })
  // 提示用户
  ElMessage.success('已退出登录')
  // 跳转到登录页
  router.push('/login')
}
</script>

<style scoped lang="less">
.layout-container {
  height: 100vh;
}

.sidebar {
  background-color: #001529;
  transition: width 0.3s;
  
  .logo {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #001529;
    color: white;
    
    h3 {
      margin: 0;
      font-size: 18px;
    }
    
    span {
      font-size: 20px;
      font-weight: bold;
    }
  }
  
  .el-menu {
    border-right: none;
    background-color: #001529;
    
    .el-menu-item,
    .el-sub-menu__title {
      color: #bfcbd9;
      
      &:hover {
        background-color: #263445;
        color: #409eff;
      }
    }
    
    .el-menu-item.is-active {
      background-color: #409eff;
      color: rgba(112, 16, 16, 0.486);
    }
  }
}

.header {
  background-color: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    
    .collapse-btn {
      margin-right: 20px;
      font-size: 18px;
    }
    
    .breadcrumb {
      font-size: 14px;
    }
  }
  
  .header-right {
    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      
      .username {
        margin: 0 8px;
        font-size: 14px;
      }
    }
  }
}

.tabs-container {
  background-color: white;
  padding: 0 20px;
  border-bottom: 1px solid #e6e6e6;
  
  .el-tabs {
    .el-tabs__header {
      margin: 0;
    }
    
    .el-tabs__nav {
      border: none;
    }
    
    .el-tabs__item {
      border: 1px solid #d9d9d9;
      margin-right: 5px;
      
      &.is-active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
}
</style>